class Product < ActiveRecord::Base
  extend Enumerize

  before_validation :downcase_all
  before_save :check_url
  # after_create :sync_to_product_a

  paginates_per 10

  mount_uploader :logo, LogoUploader
  mount_uploaders :screenshots, ScreenshotUploader

  validates :name, :summary, :description, :url, :published_at, :screenshots,
            :category, :c_name, :c_corp, :c_position,
            :c_email, :c_mobile, :c_corp_addr, presence: true
  #第二年的产品会有重名
  #validates :name, uniqueness: true
  # validates :url, format: { with: /\A(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?\z/ }
  validates :summary, length: 1..80
  validates :description, length: 1..600
  validates_inclusion_of :published_at, in: Date.new(1960, 1, 1)..Date.today
  validates :c_email, format: { with: /\A([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})\z/ }

  enumerize :status, in: [:waiting, :unapproved, :approved], default: :waiting, scope: true
  enumerize :category, in: [:app, :internet_hardware, :technology, :wechat, :media, :daily_necessaties, :open_platform, :other], default: :app, scope: true

  has_many :awards, through: :ranks
  has_many :ranks, dependent: :destroy
  has_many :innoawards, through: :innoawards_products
  has_many :innoawards_products, dependent: :destroy

  def sync_to_product_a
    return if ProductA.find_by_name(self.name)
    pa = ProductA.new(name: name, summary: summary, description: description, url: url, published_at: published_at, category: category, contacts: [{name: c_name, position: c_position, email: c_email, mobile: c_mobile}])
    pa.logo = File.new(logo.file.path)
    pa.save
    screenshots.each do |ss|
      pa.screenshots.create(file: ss.file)
    end
    pa
  end

  def check_url
    return unless weibo_changed? || url_changed?
    weibo.prepend('http://') unless weibo.start_with?('http')
    url.prepend('http://') unless url.start_with?('http')
  end

  class << self
    def search query
      where("lower(name) like ?", "%#{query.downcase}%")
    end

    def ordered
      order(created_at: :desc)
    end
  end

  def downcase_all
    self.url.downcase!
    self.c_email.downcase!
  end

  def as_my_json inno_id
    {
      name: name,
      logo: logo.url || '/assets/default_logo.jpg',
      summary: summary,
      id: id,
      created_at: created_at.strftime('%Y/%m/%d'),
      category: I18n.t("activerecord.attributes.product.category.#{category || 'empty'}"),
      status: I18n.t("activerecord.attributes.product.status.#{status}"),
      edit_path: Rails.application.routes.url_helpers.edit_admin_innoaward_product_path(innoaward_id: inno_id, id: id),
      path: Rails.application.routes.url_helpers.admin_innoaward_product_path(innoaward_id: inno_id, id: id)
    }
  end
end
